/**
 *
 *  @auth xlx_good@qq.com
 *  @date 17/6/21.
 *
 */

requirejs.config({
    baseUrl: '../../',
    paths:  {
        avalon: 'javascript/avalon.min',
        jquery: 'js/plugins/jquery/jquery-2.1.1.min',
        config: 'javascript/config',
        api: 'javascript/api',
		select2: 'js/plugins/select2/select2',
        arg: 'javascript/arg'
    },
    shim: {
        api: {
            deps: ['jquery']
        },
        layer: {
            deps: ['jquery']
        }
    }
});


(function(win, dom, requirejs, initVm){
    var vm;
    requirejs(['avalon', 'jquery', 'config', 'api', 'select2', 'arg'], function(){
        //初始化vm
        vm = initVm(dom);
    });
	win.parent.gbWareUpdate = function(callback) {
		vm.handlerFormData();
		Api.wareUpdate(vm.form, callback);
	}
	win.parent.gbWareDrafts = function(callback) {
		vm.handlerFormData();
		Api.wareUpdateToDrafts(vm.form, callback);
	}
})(window, document, requirejs, function(dom){
    var vm = avalon.define({
        $id: 'container',
        form: {
			id: '',
			pricePiece: '',
			priceUnit: '',
			numberPerBox: '',
			numberWholesale: '',
			numberInventory: '',
			saleSiteId: '',
			saleSiteName: ''
		},
		siteList: [],
		supplierSiteList: function() {
			Api.supplierSiteList(function(resp) {
				if(resp.code == 0) {
					vm.siteList = resp.data;
				} else {
					layer.msg(resp.msg);
				}
			});
		},
		wareGet: function(params) {
			Api.wareGet(params, function(resp) {
				if(resp.code == 0) {
					vm.form.id = resp.data.id;
					vm.form.pricePiece = resp.data.pricePiece;
					vm.form.priceUnit = resp.data.priceUnit;
					vm.form.numberPerBox = resp.data.numberPerBox;
					vm.form.numberWholesale = resp.data.numberWholesale;
					vm.form.numberInventory = resp.data.numberInventory;
					vm.form.saleSiteId = resp.data.saleSiteId;
					$("#saleSiteId").select2('val', vm.form.saleSiteId.split(','));
				} else {
					layer.msg(resp.msg);
				}
			});
		},
		handlerFormData: function() {
			vm.form.pricePiece = vm.form.priceUnit * vm.form.numberPerBox;
			var saleSiteId = $('#saleSiteId').val();
			if(typeof(saleSiteId) == 'string') {
				vm.form.saleSiteId = $('#saleSiteId').val();
				vm.form.saleSiteName = $('#saleSiteId').find('option:selected').text()
			} else if(saleSiteId instanceof Array) {
				vm.form.saleSiteId = $('#saleSiteId').val().join(',');
				var siteMap = {};
				for(var i=0;i<vm.siteList.length;i++) {
					siteMap[vm.siteList[i].id] = vm.siteList[i].name;
				}
				var saleSiteIdArr = vm.form.saleSiteId.split(',');
				var saleSiteNameArr = [];
				for(var i=0;i<saleSiteIdArr.length;i++) {
					saleSiteNameArr.push(siteMap[saleSiteIdArr[i]]);
				}
				vm.form.saleSiteName = saleSiteNameArr.join(',');
			}
		}
    })
	var params = Arg.parse(location.href);
    $("#saleSiteId").select2({});
    avalon.scan(dom.body);
	vm.supplierSiteList();
	vm.wareGet(params);
    return vm;
});
